using System.Diagnostics;
using System.Drawing;
using AutoClick.native;
using AutoClick.utils;

namespace AutoClick.capture.impl;
public class OptimizedBitBltCapture : IGameCapture
{
    private IntPtr _memDc;
    private IntPtr _hBitmap;
    private IntPtr _oldBitmap;
    private int _lastWidth, _lastHeight;

    public Bitmap Capture(IntPtr hWnd)
    {
        var stopWatch = Stopwatch.StartNew();

        // 获取窗口尺寸
        User32.GetWindowRect(hWnd, out Rect rect);
        var width = rect.Right - rect.Left;
        var height = rect.Bottom - rect.Top;

        // 复用内存DC和位图
        if (_memDc == IntPtr.Zero || width != _lastWidth || height != _lastHeight)
        {
            ReleaseResources();
            var hdc = User32.GetDC(IntPtr.Zero);
            _memDc = Gdi32.CreateCompatibleDC(hdc);
            _hBitmap = Gdi32.CreateCompatibleBitmap(hdc, width, height);
            _oldBitmap = Gdi32.SelectObject(_memDc, _hBitmap);
            User32.ReleaseDC(IntPtr.Zero, hdc);
            _lastWidth = width;
            _lastHeight = height;
        }

        // 直接复制到内存DC
        var desktopHdc = User32.GetDC(IntPtr.Zero);
        Gdi32.BitBlt(_memDc, 0, 0, width, height, desktopHdc, rect.Left, rect.Top, 0x00CC0020);
        User32.ReleaseDC(IntPtr.Zero, desktopHdc);

        // 转换为Bitmap（避免LockBits开销）
        var bitmap = Image.FromHbitmap(_hBitmap);

        stopWatch.Stop();
        Console.WriteLine($"OPTIMIZED BITBLT Capture Time: {stopWatch.ElapsedMilliseconds}ms");
        return bitmap;
    }

    private void ReleaseResources()
    {
        if (_memDc == IntPtr.Zero) return;
        Gdi32.SelectObject(_memDc, _oldBitmap);
        Gdi32.DeleteObject(_hBitmap);
        Gdi32.DeleteDC(_memDc);
    }
}